<!DOCTYPE html>
<html>
  
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  <meta name="author" content="Amos Zhu">
  
  
  <title>SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（三）——Nginx+Lua实现定向请求分发 | Amos的技术博客</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="stuff,redis,spring boot,nginx,memcache,">
  

  
  <meta name="description" content="上篇博文我们已经基于OpenResty搭建了Nginx+Lua的运行环境，并且编写了工程小Demo，本博文将基于上篇博文的环境来继续实现Nginx+Lua是实现定向请求分发">

  

  
    <script src="//cdn.jsdelivr.net/npm/leancloud-storage@3.11.1/dist/av-min.js" async></script>
  

  
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async></script>
  

  
    <script src="//unpkg.com/valine/dist/Valine.min.js" async></script>
  

  

  <script>
  // theme-ad's config script
  // it can be used in every script
  
  window.AD_CONFIG = {
    leancloud: {"appid":"eObxCkTJ6j4GzRxGLgiHyfJa-gzGzoHsz","appkey":"fzRMAFC6MCE11mp7mnvh4Kwe","comment":true,"count":true},
    welcome: {"enable":true,"interval":30},
    start_time: "2019-05-28",
    passwords: ["efe07af7441da2b69c4a41e42e73be4db47f66010a56900788a458354a7373ec", ],
    is_post: true,
    lock: false,
    author: "Amos Zhu",
    share: {"qq":true,"wechat":true},
    mathjax: true,
    page_type: "",
    root: "/blog/"
  };
</script>

  <script src="/blog/vendor/sha256.min.js"></script>
<script src="/blog/js/auth.js"></script>
<script src="/blog/js/index.js"></script>
<script src="/blog/vendor/qrcode.min.js"></script>

  
    <link rel="icon" href="/blog/images/favicon.ico">
    <link rel="apple-touch-icon" href="/blog/images/touch-icon.png">
  

  <link href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <link rel="stylesheet" href="/blog/css/index.css">
<link rel="stylesheet" href="/blog/styles/components/highlight/highlight.css">

  
</head>
  <body>
    <header class="site-header">
  <div class="site-header-brand">
    
      <span class="site-header-brand-title">
        <a href="/blog/">Amos Zhu</a>
      </span>
    
    
      <span class="site-header-brand-motto"> | 当浮躁的心静不下，不妨写些东西或者看会书</span>
    
  </div>
  <div class="site-header-right">
    <nav class="site-header-navigation">
      
        <a href="/blog/" target="_self">首页</a>
      
        <a href="/blog/archives/" target="_self">归档</a>
      
        <a href="/blog/tags/" target="_self">标签</a>
      
        <a href="/blog/categories/" target="_self">分类</a>
      
        <a href="/blog/redis/" target="_self">redis</a>
      
        <a href="/blog/rabbitMQ/" target="_self">rabbitMQ</a>
      
        <a href="/blog/elasticsearch" target="_self">elasticsearch</a>
      
        <a href="/blog/stuff" target="_self">stuff</a>
      
        <a href="/blog/kafka" target="_self">kafka</a>
      
        <a href="/blog/friends/" target="_self">友链</a>
      
        <a href="/blog/about/" target="_self">关于</a>
      
    </nav>
    <div class="site-header-btn">
      
        <a href="https://gitee.com/amos_zhu" target="_blank" id="site-github">
          <i class="fa fa-github-alt"></i>
        </a>
      
      <a href="javascript:void(0);" id="site-search">
        <i class="fa fa-search"></i>
      </a>
      <a href="javascript:void(0);" id="site-nav-btn">
        <i class="fa fa-ellipsis-v"></i>
      </a>
    </div>
  </div>
</header>
<nav class="table-content" id="site-nav">
  <div class="table-content-title">
    <span>导航</span>
  </div>
  <div class="table-content-main">
    <ol class="toc">
      
        <li class="toc-item">
          <a href="/blog/" target="_self">
            首页
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/archives/" target="_self">
            归档
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/tags/" target="_self">
            标签
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/categories/" target="_self">
            分类
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/redis/" target="_self">
            redis
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/rabbitMQ/" target="_self">
            rabbitMQ
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/elasticsearch" target="_self">
            elasticsearch
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/stuff" target="_self">
            stuff
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/kafka" target="_self">
            kafka
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/friends/" target="_self">
            友链
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/about/" target="_self">
            关于
          </a>
        </li>
      
    </ol>
  </div>
</nav>
<div id="site-process"></div>
    <main>
      
  <div class="passage">
  <div class="passage-meta">
    <span>
      <i class="fa fa-calendar"></i>2019-08-28
    </span>
    
      <span>
        | <a href="/blog/categories/stuff/"><i class="fa fa-bookmark"></i>stuff</a>
      </span>
    
    
      <span>
        | <i class="fa fa-unlock-alt"></i>UNLOCK
      </span>
    
  </div>
  <h1 class="passage-title">
    SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（三）——Nginx+Lua实现定向请求分发
  </h1>
  
  <article class="passage-article">
    <p></p>

<h3 id="参考之前的博文"><a href="#参考之前的博文" class="headerlink" title="参考之前的博文"></a>参考之前的博文</h3><ul>
<li><a href="https://www.jianshu.com/p/73d95bb465df" target="_blank" rel="noopener">SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（一）——三级缓存架构体系</a></li>
<li><a href="https://www.jianshu.com/p/35ab81c31044" target="_blank" rel="noopener">SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（二）——Nginx环境安装和整合Lua</a></li>
</ul>
<h3 id="请求定向实现的原理"><a href="#请求定向实现的原理" class="headerlink" title="请求定向实现的原理"></a>请求定向实现的原理</h3><p>在实现定向请求分发的功能之间，我们先了解下具体的实现的原理和逻辑</p>
<p><img src="https://s2.ax1x.com/2019/08/27/mIN5Ox.png" alt="image"></p>
<p>业务逻辑如下：</p>
<ul>
<li>分发层获取请求的关键字段，比如id</li>
<li>对id进行hash</li>
<li>hash值对应用服务器数量进行取模，获取到启动的其中的一个应用服务器</li>
<li>利用http发送请求到应用层</li>
<li>获取返回后的结果</li>
</ul>
<h3 id="环境完善"><a href="#环境完善" class="headerlink" title="环境完善"></a>环境完善</h3><p>上一篇博文中，我们已经在一个服务器上搭建了环境，接下来我们需要再准备两个环境，总共是三个环境:</p>
<table>
<thead>
<tr>
<th>服务器</th>
<th>用途</th>
</tr>
</thead>
<tbody>
<tr>
<td>192.168.56.105</td>
<td>分发层</td>
</tr>
<tr>
<td>192.168.56.106</td>
<td>应用层</td>
</tr>
<tr>
<td>192.168.56.107</td>
<td>应用层</td>
</tr>
</tbody>
</table>
<p>按照<a href="https://www.jianshu.com/p/35ab81c31044" target="_blank" rel="noopener">SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（二）——Nginx环境安装和整合Lua</a>的方法来搭建余下的两个环境，并且测试是否联通</p>
<h3 id="代码开发"><a href="#代码开发" class="headerlink" title="代码开发"></a>代码开发</h3><p>现在开始编写lua的代码，由于我们分发层需要使用http来请求其他的Nginx服务，所以我们需要先将http的依赖加载起来<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 在lualib下的resty下面来加载http的依赖</span></span><br><span class="line"><span class="built_in">cd</span> /home/work/lualib/resty</span><br><span class="line"></span><br><span class="line"><span class="comment">## 下载http_headers.lua</span></span><br><span class="line">wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua </span><br><span class="line"></span><br><span class="line">wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua</span><br></pre></td></tr></table></figure></p>
<p>下面我们开始开发，在分发层的 <code>/home/work/conf/lua/requestDirect.lua</code>中编写如下的代码</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 获取请求的url地址</span></span><br><span class="line"><span class="keyword">local</span> uri_args = ngx.req.get_uri_args()</span><br><span class="line"><span class="comment">-- 获取请求中的参数id的值</span></span><br><span class="line"><span class="keyword">local</span> id = uri_args[<span class="string">"id"</span>]</span><br><span class="line"><span class="comment">-- 目前我们准备了两个应用的nginx服务，所以我们获取应用层的ip为对象</span></span><br><span class="line"><span class="keyword">local</span> hosts = &#123;<span class="string">"192.168.56.106"</span>,<span class="string">"192.168.56.107"</span>&#125;</span><br><span class="line"><span class="comment">-- 对id记性hash</span></span><br><span class="line"><span class="keyword">local</span> hash = ngx.crc32_long(id)</span><br><span class="line"><span class="comment">-- hash值对应用层服务器的数量取模+1</span></span><br><span class="line">hash = (hash % <span class="number">2</span>) + <span class="number">1</span></span><br><span class="line"><span class="comment">-- 拼接需要访问应用层的url地址 http://192.168.56.107</span></span><br><span class="line">backend = <span class="string">"http://"</span>..hosts[hash]</span><br><span class="line"><span class="comment">-- 获取url地址中的参数 requestPath 这个路径是访问应用层的</span></span><br><span class="line"><span class="comment">-- 在本文搭建的过程中 ，主要是应用层中的 /home/work/conf/nginx.conf</span></span><br><span class="line"><span class="comment">-- 中的访问地址 </span></span><br><span class="line"><span class="keyword">local</span> requestPath = uri_args[<span class="string">"requestPath"</span>]</span><br><span class="line"><span class="comment">-- 拼接url地址后面的请求参数 http://192.168.56.107/lua?id=1</span></span><br><span class="line">requestPath = <span class="string">"/"</span>..requestPath..<span class="string">"?id="</span>..id</span><br><span class="line"><span class="comment">-- 加载http</span></span><br><span class="line"><span class="keyword">local</span> http = <span class="built_in">require</span>(<span class="string">"resty.http"</span>)</span><br><span class="line"><span class="comment">-- 创建http的客户端</span></span><br><span class="line"><span class="keyword">local</span> httpc = http.new()</span><br><span class="line"><span class="comment">-- 执行url请求</span></span><br><span class="line"><span class="keyword">local</span> resp, err = httpc:request_uri(backend,&#123;</span><br><span class="line">	method = <span class="string">"GET"</span>,</span><br><span class="line">	<span class="built_in">path</span> = requestPath</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">-- 如果失败，则返回前台失败的消息</span></span><br><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">	ngx.say(<span class="string">"request error:"</span>, err)</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 如果请求成功，打印请求内容</span></span><br><span class="line">ngx.say(resp.body)</span><br><span class="line"><span class="comment">-- http客户端关闭</span></span><br><span class="line">httpc:<span class="built_in">close</span>()</span><br></pre></td></tr></table></figure>
<p>代码开发完成之后， 我们重新加载下<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 编译</span></span><br><span class="line">nginx -t</span><br><span class="line"><span class="comment">## 重新加载</span></span><br><span class="line">nginx -s reload</span><br></pre></td></tr></table></figure></p>
<p>在浏览器上请求:<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 请求一 requestPath的路径目前只能是lua，为了请求到</span></span><br><span class="line"><span class="comment">## 应用Nginx层的lua访问</span></span><br><span class="line">http://192.168.56.105/lua?requestPath=lua&amp;id=1</span><br><span class="line"></span><br><span class="line">http://192.168.56.105/lua?requestPath=lua&amp;id=2</span><br></pre></td></tr></table></figure></p>
<p>可以变更id的值，看看请求返回的值有很什么变化</p>
<p>如果在执行的过程中，出现错误了，可以查看nginx的日志记录<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 查看 nginx的错误日志</span></span><br><span class="line">tail -1000f /usr/<span class="built_in">local</span>/openresty/nginx/logs/error.log</span><br></pre></td></tr></table></figure></p>
<p>至此我们就全部完成了定向请求分发的功能，下一篇博文，我们结合后台框架来整合nginx和redis以及tomcat堆缓存的交互，完成三级缓存架构的功能</p>
  </article>
  <aside class="table-content" id="site-toc">
  <div class="table-content-title">
    <i class="fa fa-arrow-right fa-lg" id="site-toc-hide-btn"></i>
    <span>目录</span>
  </div>
  <div class="table-content-main">
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#参考之前的博文"><span class="toc-text">参考之前的博文</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#请求定向实现的原理"><span class="toc-text">请求定向实现的原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#环境完善"><span class="toc-text">环境完善</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#代码开发"><span class="toc-text">代码开发</span></a></li></ol>
  </div>
</aside>
  
    <aside class="passage-copyright">
      <div>本文作者: Amos Zhu</div>
      
        <div>
          原文链接: 
          <a href target="_blank">http://amos_zhu.gitee.io/passages/SpringBoot-Redis-MemCache-Nginx-Lua实现三级缓存架构（三）——Nginx-Lua实现定向请求分发/</a>
        </div>
      
      <div>
        版权声明: 本博客所有文章除特别声明外, 均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议. 转载请注明出处!
      </div>
    </aside>
  
  
    <div class="passage-tags">
     
      <a href="/blog/tags/redis/"><i class="fa fa-tags"></i>redis</a>
     
      <a href="/blog/tags/spring-boot/"><i class="fa fa-tags"></i>spring boot</a>
     
      <a href="/blog/tags/nginx/"><i class="fa fa-tags"></i>nginx</a>
     
      <a href="/blog/tags/memcache/"><i class="fa fa-tags"></i>memcache</a>
    
    </div>
  
</div>

    </main>
    
      
<div class="site-comment-contanier" data-plateform="leancloud">
  
    <p id="site-comment-info">
      <i class="fa fa-spinner fa-spin"></i> 评论加载中
    </p>
    <div id="site-comment"></div>
  
</div>
    
    <div class="site-footer-wrapper">
  <footer class="site-footer">
    
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">博客推荐</h5>
          
            <span class="site-footer-item">
              <a href="http://youzhixueyuan.com/series/java" target="_blank">优知学院</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://ruanyifeng.com/" target="_blank">阮一峰的个人网站</a>
            </span>
          
        </div>
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">系列教程</h5>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/redis" target="_blank">Redis系列教程</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/rabbitMQ/" target="_blank">RabbitMQ教程</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/kafka/" target="_blank">Kafka架构探险</a>
            </span>
          
        </div>
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">抓到我</h5>
          
            <span class="site-footer-item">
              <a href="https://gitee.com/amos_zhu" target="_blank">Gitee</a>
            </span>
          
            <span class="site-footer-item">
              <a href="https://blog.csdn.net/wdcl2468" target="_blank">CSDN</a>
            </span>
          
            <span class="site-footer-item">
              <a href="https://www.jianshu.com/u/2dbe61b1f3c3" target="_blank">简书</a>
            </span>
          
        </div>
      
    
    <div class="site-footer-info">
      <i class="fa fa-clock-o"></i> 本站已稳定运行<span id="site-time"></span>
    </div>
    
      <div class="site-footer-info">
        <i class="fa fa-paw"></i> 您是本站第 <span id="site-count"></span> 位访客
      </div>
    
    
      <div class="site-footer-info">
        <i class="fa fa-at"></i> Email: amoszhu@aliyun.com
      </div>
    
    <div class="site-footer-info">
      <i class="fa fa-copyright"></i> 
      2019 <a href="https://github.com/dongyuanxin/theme-ad/" target="_blank">Theme-AD</a>.
      Created by <a href="https://godbmw.com/" target="_blank">GodBMW</a>.
      All rights reserved.
    </div>
  </footer>
</div>
    <div id="site-layer" style="display:none;">
  <div class="site-layer-content">
    <div class="site-layer-header">
      <span class="site-layer-header-title" id="site-layer-title"></span>
      <i class="fa fa-close" id="site-layer-close"></i>
    </div>
    <div class="site-layer-body" id="site-layer-container">
      <div class="site-layer-input" id="site-layer-search" style="display: none;">
        <div class="site-layer-input-choose">
          <a href="javascript:void(0);" title="Change Search Engine">Google</a>
        </div>
        <input type="text">
        <i class="fa fa-search"></i>
      </div>
      
        <div class="site-layer-reward" id="site-layer-reward" style="display: none;">
          
            <div>
              <img src="/blog/images/wechat.png" alt="WeChat">
              
                <p>WeChat</p>
              
            </div>
          
            <div>
              <img src="/blog/images/alipay.png" alt="AliPay">
              
                <p>AliPay</p>
              
            </div>
          
        </div>
      
      <div id="site-layer-welcome" style="display:none;"></div>
    </div>
  </div>
</div>
    

<div class="bottom-bar">
  <div class="bottom-bar-left">
    <a href="/blog/passages/SpringBoot-Redis-MemCache-Nginx-Lua实现三级缓存架构（四）——Nginx-Redis-Cache实现三级缓存架构/" data-enable="true">
      <i class="fa fa-arrow-left"></i>
    </a>
    <a href="/blog/passages/SpringBoot-Redis-MemCache-Nginx-Lua实现三级缓存架构（一）——三级缓存架构体系/" data-enable="true">
      <i class="fa fa-arrow-right"></i>
    </a>
  </div>
  <div class="bottom-bar-right">
    <a href="javascript:void(0);" data-enable="true" id="site-toc-show-btn">
      <i class="fa fa-bars"></i>
    </a>
    
      <a href="#site-comment" data-enable="true">
        <i class="fa fa-commenting"></i>
      </a>
    
    <a href="javascript:void(0);" id="site-toggle-share-btn">
      <i class="fa fa-share-alt"></i>
    </a>
    
      <a href="javascript:void(0);" id="site-reward">
        <i class="fa fa-thumbs-up"></i>
      </a>
    
    <a href="javascript:void(0);" id="back-top-btn">
      <i class="fa fa-chevron-up"></i>
    </a>
  </div>
</div>
    <div id="share-btn">
  
  
  
  
    <a id="share-btn-qq" href="javascript:void(0);" target="_blank">
      <i class="fa fa-qq"></i>
    </a>
  
  
    <a id="share-btn-wechat" href="javascript:void(0);" target="_blank">
      <i class="fa fa-wechat"></i>
    </a>
  
</div>
    


  <script async>
  (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      }
      else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>



  <script async>
    (function(){
    var src = (document.location.protocol == "http:") ? "http://js.passport.qihucdn.com/11.0.1.js?":"https://jspassport.ssl.qhimg.com/11.0.1.js?";
    document.write('<script src="' + src + '" id="sozz"><\/script>');
    })();
  </script>


    
  </body>
</html>